/*
 * To change this template, chooser Tools | Templates
 * and open the template in the editor.
 */

package amd.core;

import amd.core.extraction.DocExtractor;
import amd.core.search.SearchDocRelevant;
import amd.core.search.SearchDocSimilar;
import amd.database.ConnectDB;
import amd.database.DbDocument;
import amd.database.QueryNoResultException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @author Latifah Dwi Nurachma
 */
public class TextCommandListener {
    private File currentDir;
    private FileFilter fileFilter;
    private String targetPath;
    private String sourcePath;
    private String textEditorPath;
    private String pdfReaderPath;
    private ConnectDB conn;
    private String logFile;
    private float treshold;
    private WriteToFileTxt txtWriter;

    private Properties properties;
    //private FrameMenuUpload menuUpload;
    
    public TextCommandListener() throws Exception{
        logFile = "log.txt";
        txtWriter = new WriteToFileTxt(logFile);

//        PrintStream errp=null;
//        errp = new PrintStream(new FileOutputStream(logFile, true));
//        System.setOut(errp);

        properties = LoadXmlProperties.readProperties("config.xml");

        conn = new ConnectDB(properties.getProperty("database.url"),
                properties.getProperty("database.username"),
                properties.getProperty("database.password"));

        sourcePath = properties.getProperty("folder.source");
        if(!new File(sourcePath).exists()){
            new File(sourcePath);
        }
        targetPath = properties.getProperty("folder.target");
        if(!new File(targetPath).exists()){
            new File(targetPath);
        }

        textEditorPath = properties.getProperty("program.texteditor","C:\\WINDOWS\\system32\\notepad.exe");
        pdfReaderPath = properties.getProperty("program.pdfreader");
        treshold = Float.valueOf(properties.getProperty("treshold"));

        currentDir = new File(".");
        fileFilter = new FileFilter() {
            @Override
            public boolean accept(File f) {
                return (f.isDirectory() || f.getName().endsWith(".pdf"));
            }
            @Override
            public String getDescription() {
                return "PDF Files";
            }
        };

    }


    public  void ekstrakDokumen() {
        DocExtractor.extractAllDocument(conn, new File(sourcePath), new File(targetPath));
        //JOptionPane.showMessageDialog(frame, "Dokumen telah selesai diekstrak","Berhasil",JOptionPane.INFORMATION_MESSAGE,null);
    }

    public void login() {

    }

    public ArrayList<ArrayList<String>> searchDocumentByKeyword(String inputKeyword, int page){
        ArrayList<ArrayList<String>> listDoc = new ArrayList<ArrayList<String>>();
        try {
            listDoc = SearchDocRelevant.search(conn, inputKeyword, treshold, page);
        } catch (QueryNoResultException ex) {
        }
        return listDoc;
    }

    public ArrayList<ArrayList<String>> searchDocumentByKeyword(String inputKeyword){
        ArrayList<ArrayList<String>> listDoc = new ArrayList<ArrayList<String>>();
        try {
            listDoc = SearchDocRelevant.search(conn, inputKeyword, treshold);
        } catch (QueryNoResultException ex) {
        }
        return listDoc;
    }

    public ArrayList<ArrayList<String>>  searchDocumentSimilar(String idDocReff){
        ArrayList<ArrayList<String>> docSimilar= null;
        try {
             docSimilar = SearchDocSimilar.search(conn, idDocReff);
        } catch (QueryNoResultException ex) {
        }
        return docSimilar;
    }


    public ArrayList<ArrayList<String>> searchDocumentSimilar(String idDocReff, int page){
        ArrayList<ArrayList<String>> docSimilar= new ArrayList<ArrayList<String>>();
        try {
            docSimilar = SearchDocSimilar.search(conn, idDocReff, treshold, page);
        } catch (QueryNoResultException ex) {
            //System.out.println("Pencarian dokumen similar gagal.");
        }
        return docSimilar;
    }

    public void uploadDocument(){
//        JFileChooser chooser = new JFileChooser();
//        chooser.setCurrentDirectory(currentDir);
//        chooser.setFileFilter(fileFilter);
//        chooser.setAcceptAllFileFilterUsed(false);
//        int result = chooser.showOpenDialog(frame);
//        if (result == JFileChooser.APPROVE_OPTION) {
//            File file = chooser.getSelectedFile();
//            String name = chooser.getSelectedFile().getPath();
//            currentDir = new File(name).getParentFile();
//            if(file.getName().endsWith(".pdf")){
//                try {
//                    FileOperations.copyFilePdf(name, sourcePath);
//                    JOptionPane.showMessageDialog(frame, "File " + file.getName() + " telah berhasil di upload.", "Berhasil", JOptionPane.INFORMATION_MESSAGE, null);
//                    System.out.println(CurrentDateAndTime.getDateTime() + " Upload dokumen dari " + file.getPath() + " ke "+ sourcePath +" berhasil.");
//
//                } catch (Exception ex) {
//                    JOptionPane.showMessageDialog(frame,
//                            "Dokumen gagal di-upload\n"+ex.getMessage(),
//                            "Gagal", JOptionPane.INFORMATION_MESSAGE, null);
//                }
//            }
//            else{
//                //message box bahwa dia mengupload file bukan pdf
//                JOptionPane.showMessageDialog(frame, "File "+ file.getName() + " tidak berformat PDF.\nFile tidak berhasil diupload.","Gagal",JOptionPane.WARNING_MESSAGE,null);
//            }
//        }
    }

    public String browseDocument() {
//        JFileChooser chooser = new JFileChooser();
//        chooser.setCurrentDirectory(currentDir);
//        chooser.setFileFilter(fileFilter);
//        chooser.setAcceptAllFileFilterUsed(false);
//        int result = chooser.showOpenDialog(frame);
//        String fileName = "";
//        if (result == JFileChooser.APPROVE_OPTION) {
//            File file = chooser.getSelectedFile();
//            String name = chooser.getSelectedFile().getPath();
//            currentDir = new File(name).getParentFile();
//            if(file.getName().endsWith(".pdf")){
//                fileName = file.getPath();
//            }
//            else{
//                //message box bahwa dia mengupload file bukan pdf
//                JOptionPane.showMessageDialog(frame, "File "+ file.getName() + " tidak berformat PDF.\nFile tidak berhasil diupload.","Gagal",JOptionPane.WARNING_MESSAGE,null);
//            }
//        }
//        return fileName;
        return "";
    }

    public void openPdfDocument(String docPath){
        try {
            Runtime load = Runtime.getRuntime();
            //System.out.println(pdfReaderPath + " " + docPath);
            load.exec(pdfReaderPath + " " + docPath);
        } catch (IOException ex) {
            txtWriter.writeln(ex.toString());
        }

    }

    public void uploadDocument(String docPath) {
        if (docPath.endsWith(".pdf")){
            try {
                FileOperations.copyFilePdf(docPath, sourcePath);
                txtWriter.writeln(CurrentDateAndTime.getDateTime() + " Upload dokumen dari " + docPath + " ke "+ sourcePath +" berhasil.");
                System.out.println(CurrentDateAndTime.getDateTime() + " Upload dokumen dari " + docPath + " ke "+ sourcePath +" berhasil.");
            } catch (Exception ex) {
                txtWriter.writeln("Upload dokumen dari " + docPath + " gagal.");
                System.out.println("Upload dokumen dari " + docPath + " gagal.");
            }
        }
        else{
            System.out.println("Dokumen yang akan diupload tidak berformat .pdf. Upload dokumen gagal.");
        }

    }

    public void viewLog() {
        try {
            Runtime load = Runtime.getRuntime();
            load.exec(textEditorPath + " " + logFile);
        } catch (Exception ex) {
         }
    }

    public ArrayList<String> getDocumentInfo(String idDoc) {
        ArrayList<String> listInfo = new ArrayList<String>();
        try {
            listInfo = DbDocument.getDataDocument(conn, idDoc);
        } catch (QueryNoResultException ex) {
        }
        return listInfo;
    }

    public String getTargetPath() {
        return targetPath;
    }

    public void close() {
        txtWriter.close();
    }

}
